import request from '@/utils/request';
import { downloadFileByData } from '@/utils/download';
import type { CustomersStudentQueryParams, CustomersStudentModel } from '@/api/customer/student/CustomersStudentManagementApi';
import type { CustomersInfoQueryParams, CustomersInfoModel } from '@/api/customer/customerinfo/CustomersInfoManagementApi';

/**
 * 客户关系 实体类型定义
 *
 * @author guagua
 * @date 2025-06-29 00:14:23
 */
export interface CustomerStudentRelationModel {
    /** 主键ID */
    id?: string;

    status: number;

    tags?: string;

    /** 背景颜色 */
    bgColor?: string;

    students: CustomersStudentModel[],
    customer: CustomersInfoModel,
    /** 客户ID */
    customerId?: string;

    /** 学员ID */
    studentId?: string;

    /** 关系 */
    relationType: string;

    /** 是否主要联系人(0否 1是) */
    isPrimary?: string;

    // ========================================
    // 基础信息字段
    // ========================================

    /** 来源渠道 */
    sourceChannel?: string;


    /** 优先级 */
    priority?: string;

    /** 备注说明 */
    remark?: string;

    /** 父级主键集合 */
    orgIds?: string;

    /** 修改人 */
    updateBy?: string;

    /** 创建时间 */
    createTime?: Date;

    /** 创建者 */
    createBy?: string;

    /** 修改时间 */
    updateTime?: string;

    /** 乐观锁 */
    version?: number;

}

/**
 * 分页查询参数类型
 */
export interface CustomerStudentRelationQueryParams {
    /** 页码 */
    pageNo?: number;

    /** 每页条数 */
    pageSize?: number;

    // ========================================
    // 关系信息查询条件
    // ========================================
    /** 客户ID */
    customerId_EQ?: string;
    /** 学员ID */
    studentId_EQ?: string;
    /** 关系 */
    relationType_EQ?: string;
    /** 是否主要联系人(0否 1是) */
    isPrimary_EQ?: string;
    /** 来源渠道 */
    sourceChannel_EQ?: string;

    // ========================================
    // 时间范围查询条件
    // ========================================
    /** 创建时间开始 */
    createTime_GE?: string;
    /** 创建时间结束 */
    createTime_LE?: string;
    /** 建立日期开始 */
    establishDate_GE?: string;
    /** 建立日期结束 */
    establishDate_LE?: string;

    /** 创建者 */
    createBy_EQ?: string;

    /**
     * 学生查询条件
     */
    studentQP?: CustomersStudentQueryParams;

    /**
     * 家长查询条件
     */
    customerQP?: CustomersInfoQueryParams;

    /**
     * id
     */
    id_EQ?: string;

}

/**
 * API 响应类型
 */
export interface ApiResponse<T = any> {
    code: number;
    msg: string;
    data: T;
    timestamp: number;
}

/**
 * 分页响应数据类型
 */
export interface PageResult<T> {
    rows: T[];
    total: number;
    size: number;
    current: number;
    pages: number;
}

/**
 * 获取客户关系分页列表
 * @param params 查询参数
 * @returns Promise<ApiResponse<PageResult<CustomerStudentRelationModel>>>
 */
export function getList(params: CustomerStudentRelationQueryParams): Promise<ApiResponse<PageResult<CustomerStudentRelationModel>>> {
    return request({
        url: '/api/v1/customer/customerrelation/findPage',
        method: 'get',
        params
    });
}

/**
 * 获取客户关系详细信息分页列表（包含客户和学生信息）
 * @param params 查询参数
 * @returns Promise<ApiResponse<PageResult<CustomerStudentRelationModel>>>
 */
export function getListWithDetails(
    params: CustomerStudentRelationQueryParams
): Promise<ApiResponse<PageResult<CustomerStudentRelationModel>>> {
    return request({
        url: '/api/v1/customer/customerrelation/findPageWithDetailsV2',
        method: 'post',
        data: params
    });
}

/**
 * 获取客户关系详情（包含客户和学生信息）
 * @param id 主键ID
 * @returns Promise<ApiResponse<CustomerStudentRelationModel>>
 */
export function getByIdWithDetails(id: string): Promise<ApiResponse<CustomerStudentRelationModel>> {
    return request({
        url: `/api/v1/customer/customerrelation/getWithDetails/${id}`,
        method: 'get'
    });
}

/**
 * 新增客户关系
 * @param data 新增数据
 * @returns Promise<ApiResponse<CustomerStudentRelationModel>>
 */
export function doInsert(data: Partial<CustomerStudentRelationModel>): Promise<ApiResponse<CustomerStudentRelationModel>> {
    return request({
        url: '/api/v1/customer/customerrelation/insert',
        method: 'post',
        data
    });
}

/**
 * 更新客户关系
 * @param data 更新数据
 * @returns Promise<ApiResponse<CustomerStudentRelationModel>>
 */
export function doUpdate(data: CustomerStudentRelationModel): Promise<ApiResponse<CustomerStudentRelationModel>> {
    return request({
        url: '/api/v1/customer/customerrelation/update',
        method: 'post',
        data
    });
}

/**
 * 删除客户关系
 * @param params 删除参数
 * @returns Promise<ApiResponse<boolean>>
 */
export function doDelete(params: { id: string }): Promise<ApiResponse<boolean>> {
    return request({
        url: '/api/v1/customer/customerrelation/del',
        method: 'post',
        params
    });
}

/**
 * 批量删除客户关系
 * @param params 批量删除参数
 * @returns Promise<ApiResponse<boolean>>
 */
export function doDeleteAll(params: { ids: string }): Promise<ApiResponse<boolean>> {
    return request({
        url: '/api/v1/customer/customerrelation/delAll',
        method: 'post',
        params
    });
}

/**
 * 导出Excel 目前只支持一层参数传递
 * @param params 导出参数
 * @returns Promise<void>
 */
export async function doExportExcel(params: CustomerStudentRelationQueryParams): Promise<void> {
    const authURL = '/api/v1/customer/customerrelation/excel/auth/export';

    const downloadURL = '/api/v1/customer/customerrelation/excel/export/';

    try {
        // 认证
        const response: ApiResponse<string> = await request({
            url: authURL,
            method: 'get',
            params
        });

        if (response.data) {
            // 下载文件
            downloadFileByData(downloadURL + response.data, params);
        }
    } catch (error) {
        console.error('导出Excel失败:', error);
        throw error;
    }
}

/**
 * 下载导入模版
 * @returns Promise<void>
 */
export async function doDownloadTemplate(): Promise<void> {
    const authURL = '/api/v1/customer/customerrelation/excel/auth/import-template-export';

    const downloadURL = '/api/v1/customer/customerrelation/excel/export/';

    try {
        // 认证
        const response: ApiResponse<string> = await request({
            url: authURL,
            method: 'get'
        });

        if (response.data) {
            // 下载文件
            downloadFileByData(downloadURL + response.data, {});
        }
    } catch (error) {
        console.error('下载模板失败:', error);
        throw error;
    }
}

/**
 * 导入Excel
 * @param data 上传的文件数据
 * @returns Promise<ApiResponse<any>>
 */
export function doImportExcel(data: FormData): Promise<ApiResponse<any>> {
    return request({
        url: '/api/v1/customer/customerrelation/importExcel',
        method: 'post',
        // 最长超时时间 3 分钟
        timeout: 180000,
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        data
    });
}

/**
 * 获取客户关系详情
 * @param id 主键ID
 * @returns Promise<ApiResponse<CustomerStudentRelationModel>>
 */
export function getById(id: string): Promise<ApiResponse<CustomerStudentRelationModel>> {
    return request({
        url: `/api/v1/customer/customerrelation/findById/${id}`,
        method: 'get'
    });
}

/**
 * 启用/禁用客户关系
 * @param params 启用禁用参数
 * @returns Promise<ApiResponse<boolean>>
 */
export function doEnable(params: { id: string; enable: boolean }): Promise<ApiResponse<boolean>> {
    return request({
        url: '/api/v1/customer/customerrelation/enable',
        method: 'post',
        params
    });
}

/**
 * 根据客户ID查询所有关系
 * @param customerId 客户ID
 * @returns Promise<ApiResponse<CustomerStudentRelationModel[]>>
 */
export function findByCustomerId(customerId: string): Promise<ApiResponse<CustomerStudentRelationModel[]>> {
    return request({
        url: `/api/v1/customer/customerrelation/findByCustomerId/${customerId}`,
        method: 'get'
    });
}

/**
 * 根据学生ID查询所有关系
 * @param studentId 学生ID
 * @returns Promise<ApiResponse<CustomerStudentRelationModel[]>>
 */
export function findByStudentId(studentId: string): Promise<ApiResponse<CustomerStudentRelationModel[]>> {
    return request({
        url: `/api/v1/customer/customerrelation/findByStudentId/${studentId}`,
        method: 'get'
    });
}

/**
 * 查询客户的主要联系人关系
 * @param customerId 客户ID
 * @returns Promise<ApiResponse<CustomerStudentRelationModel>>
 */
export function findPrimaryByCustomerId(customerId: string): Promise<ApiResponse<CustomerStudentRelationModel>> {
    return request({
        url: `/api/v1/customer/customerrelation/findPrimaryByCustomerId/${customerId}`,
        method: 'get'
    });
}

/**
 * 查询客户的所有学生
 * @param customerId 客户ID
 * @returns Promise<ApiResponse<any[]>>
 */
export function findStudentsByCustomerId(customerId: string): Promise<ApiResponse<any[]>> {
    return request({
        url: `/api/v1/customer/customerrelation/findStudentsByCustomerId/${customerId}`,
        method: 'get'
    });
}

/**
 * 批量创建客户学生关系
 * @param data 批量创建数据
 * @returns Promise<ApiResponse<boolean>>
 */
export function batchCreateRelations(data: {
    customerId: string;
    students: Array<{
        studentId?: string;
        relationType: string;
        studentName?: string;
        studentGender?: string;
        studentGrade?: string;
        studentSchool?: string;
    }>;
    baseInfo: {
        sourceChannel?: string;
        priority?: string;
        remark?: string;
    };
}): Promise<ApiResponse<boolean>> {
    return request({
        url: '/api/v1/customer/customerrelation/batchCreateRelations',
        method: 'post',
        data
    });
}

/**
 * 设置主要联系人
 * @param relationId 关系ID
 * @param customerId 客户ID
 * @returns Promise<ApiResponse<boolean>>
 */
export function setPrimaryContact(relationId: string, customerId: string): Promise<ApiResponse<boolean>> {
    return request({
        url: '/api/v1/customer/customerrelation/setPrimaryContact',
        method: 'post',
        params: {
            relationId,
            customerId
        }
    });
}

/**
 * 统计关系类型分布
 * @returns Promise<ApiResponse<Array<{relation_type: string, count: number}>>>
 */
export function getRelationTypeStatistics(): Promise<ApiResponse<Array<{ relation_type: string; count: number }>>> {
    return request({
        url: '/api/v1/customer/customerrelation/statistics/relationType',
        method: 'get'
    });
}

/**
 * 统计关系状态分布
 * @returns Promise<ApiResponse<Array<{relation_status: string, count: number}>>>
 */
export function getRelationStatusStatistics(): Promise<ApiResponse<Array<{ relation_status: string; count: number }>>> {
    return request({
        url: '/api/v1/customer/customerrelation/statistics/relationStatus',
        method: 'get'
    });
}
